<template>
  <TablePage :class="projectId ? 'p-0' : ''">
    <template #top>
      <SearchForm
        v-model:columns="columns"
        :title="t('routes.equipmentManage')"
        :title-size-class="projectId !== undefined ? ' text-xl font-semibold' : 'text-2xl font-semibold'"
        :keyword-search-data="searchModel"
        :required-keys="requiredKeys"
        :select-data="selectData"
        :add-btn-oper-type="OperPermissionType.MANAGE"
        add-btn-text="新增设备"
        :del-btn-oper-type="OperPermissionType.MANAGE"
        del-btn-text="删除"
        :del-btn-props="{
          disabled: selectedRowKeys.length === 0,
          onClick: delEquipmentsFn,
        }"
        :del-btn-disabled-mes="selectedRowKeys.length === 0 ? '请选择要删除的设备' : ''"
        @search="handleSearch"
        @add="handleAddEquipment"
      >
      </SearchForm>
    </template>
    <SlTable
      :columns="columns"
      row-key="equipmentId"
      :data-source="tableData"
      :loading="tableLoading"
      :pagination="pagination"
      :search-model="applySearchModel"
      :row-selection="rowSelection"
      :ignore-keys="projectId ? ['projectId'] : ['']"
    >
      <template #bodyCell="{ column, record }">
        <a-space v-if="column.key === 'oper'">
          <PermissionBtn
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="gatewaySetFn(record)"
          >
            绑定点位
          </PermissionBtn>
          <PermissionBtn :btn-props="{ type: 'link' }" :oper-type="OperPermissionType.MANAGE" @click="editFn(record)">
            编辑
          </PermissionBtn>
          <PermissionBtn
            :oper-type="OperPermissionType.MANAGE"
            :btn-props="{ type: 'link', danger: true }"
            @click="setShowOptions({ action: CURDAction.DELETE, record })"
          >
            删除
          </PermissionBtn>
        </a-space>
        <a
          v-if="column.dataIndex === 'equipmentName'"
          :href="`/#/equipmentDetail/${record.equipmentId}/overview`"
          target="_blank"
        >
          <EllipsisText :max-len="20" :text="record.equipmentName" />
        </a>

        <div v-if="column.dataIndex === 'isRead'" :style="{ width: '80px' }">
          {{ record.isRead ? "是" : "否" }}
        </div>
        <StateTag
          v-if="column.key === 'isOnline'"
          :color="record.isOnline ? '#38CE7B' : colors.secondary"
          :value="record.isOnline ? '在线' : '离线'"
          class="h-6 ml-2 px-2"
        ></StateTag>
        <a-space v-if="column.key === 'oper'">
          <PermissionBtn
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showUpdateModal(record)"
            >{{ t("common.edit") }}</PermissionBtn
          >
          <PermissionBtn
            :btn-props="{ type: 'link', danger: true }"
            :oper-type="OperPermissionType.MANAGE"
            @click="deleteRecord(record)"
            >{{ t("common.delete") }}</PermissionBtn
          >
        </a-space>
      </template>
    </SlTable>
    <CURDDialog
      id-key="equipmentId"
      :model="equipmentModel"
      :columns="columns"
      delete-message="您确定要删除该设备吗？"
      :show-options="showOptions"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      :reload-table="reloadTable"
      :get-delete-params="getUserDeleteParams"
      @before-ok="functionBeforeOk"
      @before-show="beforeShow"
      @ok="handleSuccess"
    />
    <CreateEquipmentModal v-model:visible="createVisible" :project-id="projectId" @success-fn="reloadTable" />
    <GatewayBindModal
      v-model:visible="gatewayBindVisible"
      :options="curEquipmentOption"
      :inset-cls="projectId ? '' : undefined"
    />
    <EditEquipmentModal v-model:id="curEquipmentId" @success-fn="reloadTable" />
  </TablePage>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch, nextTick } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { colors } from "/@/style/style";
import SearchForm from "/@/components/SearchForm.vue";
import { useCURD } from "/@/hooks/useCURD";
import { OperPermissionType } from "/@/api/aiot/role/models";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import EllipsisText from "/@/components/common/EllipsisText.vue";
import EditEquipmentModal from "./EditEquipmentModal.vue";
import GatewayBindModal from "./GatewayBindModal.vue";
import CreateEquipmentModal from "./CreateEquipmentModal.vue";
import { CURDAction, CURDModalEvent, FormItemData, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import TablePage from "/@/components/TablePage.vue";
import SlTable from "/@/components/SlTable.vue";
import { Api, pageEquipmentType } from "/@/api/aiot/equipment";
import type { TableRecord } from "/@/api/models";
import { message } from "ant-design-vue";
import { SelectItem } from "/@/types/components";
import { EquipmentItem, GatewayModalPropsOptions } from "/@/api/aiot/equipment/models";
import { projectsPage } from "/@/api/aiot/projectManage";
import { equipmentTypePage, pageEquipmentCategoryEnter } from "/@/api/aiot/deviceType";
const { t } = useI18n();
const props = defineProps<{
  projectId?: string;
}>();
const createVisible = ref<boolean>(false);
const requiredKeys = ["equipmentName", "equipmentNo", "equipmentType"];

const selectData = ref<SelectItem[]>([
  {
    label: "所属项目",
    value: "",
    key: "projectId",
    props: { fieldNames: { label: "projectName", value: "projectId" } },
    options: [],
  },
  {
    label: "设备类别",
    value: "",
    key: "equipmentCategoryId",
    isTreeSelect: true,
    containerWidth: 180,
    props: {
      treeData: [],
      fieldNames: { label: "equipmentCategoryName", value: "equipmentCategoryId" },
    },
  },
  {
    label: "设备类型",
    value: "",
    key: "defaultEquipmentTypeId",
    containerWidth: 180,
    options: [],
    props: {
      fieldNames: { label: "defaultEquipmentTypeName", value: "defaultEquipmentTypeId" },
    },
  },
]);
watch(
  () => props.projectId,
  (val) => {
    if (val) {
      if (selectData.value[0]) {
      }
    }
  }
);
const showOptions = ref<ShowCURDModalOptions>();
const searchModel = [{ key: "searchText", label: "设备编号/名称" }];
const {
  tableData,
  tableLoading,
  curd,
  reloadTable,
  pagination,
  searchModel: applySearchModel,
} = useCURD<EquipmentItem>({
  createUrl: Api.addEquipment,
  deleteUrl: Api.deleteEquipmentByIds,
  getPageUrl: Api.pageEquipments,
  updateUrl: Api.updateEquipment,
  loadOnMounted: false,
});

onMounted(async () => {
  // const data = await pageEquipmentType();
  // 获取设备类别数据
  let equipmentCategoryData = (await pageEquipmentCategoryEnter())?.records || [];
  let equipmentTypeList = await equipmentTypePage(false);
  if (props.projectId) {
    selectData.value = [
      {
        label: "设备类别",
        value: "",
        key: "equipmentCategoryId",
        isTreeSelect: true,
        containerWidth: 180,
        props: {
          treeData: [],
          fieldNames: { label: "equipmentCategoryName", value: "equipmentCategoryId" },
        },
      },
      {
        label: "设备类型",
        value: "",
        key: "defaultEquipmentTypeId",
        containerWidth: 180,
        options: [],
        props: {
          fieldNames: { label: "defaultEquipmentTypeName", value: "defaultEquipmentTypeId" },
        },
      },
    ];
    let props = selectData.value[0].props;
    if (equipmentCategoryData && props) {
      props.loading = false;
      props.treeData = equipmentCategoryData;
      props.treeData.unshift({ equipmentCategoryName: "全部", equipmentCategoryId: "" });
    }
    if (equipmentTypeList && selectData.value && selectData.value[1]) {
      selectData.value[1].options = equipmentTypeList.records || [];
      selectData.value[1].options.unshift({ defaultEquipmentTypeName: "全部", defaultEquipmentTypeId: "" });
    }
  } else {
    // 所属项目下拉数据
    const projectList = await projectsPage();
    selectData.value[0].options = projectList?.records || [];
    selectData.value[0].options?.unshift({ projectName: "全部", projectId: "" });
    let props = selectData.value[1].props;
    // 设备类别下拉数据
    if (equipmentCategoryData && props) {
      props.loading = false;
      props.treeData = equipmentCategoryData;
      props.treeData.unshift({ equipmentCategoryName: "全部", equipmentCategoryId: "" });
    }
    // 设备类型下拉数据
    if (equipmentTypeList && selectData.value) {
      console.info("设备类型");
      selectData.value[2].options = equipmentTypeList.records || [];
      selectData.value[2].options.unshift({ defaultEquipmentTypeName: "全部", defaultEquipmentTypeId: "" });
    }
  }
  reloadTable({ model: { projectId: props.projectId || "" } });
});
const equipmentModel = ref({});
const modelFormSetting: FormItemData[] = [];
const columns = ref<Array<TableRecord>>([
  {
    title: t("aiot.equpiment.equipmentName"),
    dataIndex: "equipmentName",
    width: "120px",
  },
  {
    title: t("aiot.equpiment.equipmentNo"),
    dataIndex: "equipmentNo",
    width: "120px",
  },
  {
    title: "所属项目",
    dataIndex: "projectName",
    width: "120px",
  },
  {
    title: "设备类别",
    dataIndex: "equipmentCategoryName",
    width: "120px",
  },
  {
    title: "设备机型",
    dataIndex: "equipmentType",
    width: "120px",
  },

  {
    title: "所属网关",
    dataIndex: "gatewayName",
    width: "120px",
  },
  {
    title: "设备状态",
    dataIndex: "isOnline",
    width: "120px",
  },
  {
    title: t("aiot.equpiment.brandName"),
    dataIndex: "brandName",
    width: "120px",
  },
  {
    key: "oper",
    title: "操作",
    fixed: "right",
    width: "100px",
  },
]);

function beforeShow(e) {
  if (e.action === CURDAction.UPDATE || e.action === CURDAction.CHECK) {
  }
}
function handleSearch(model) {
  model.projectId ? "" : (model.projectId = props.projectId);
  reloadTable({ model, current: 1 });
}

function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function deleteRecord(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
function functionBeforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as EquipmentItem;
    if (e.action === CURDAction.CREATE) {
      // model.parentIndustryInnerId = 0;
    }
  }
}
function handleAddEquipment() {
  createVisible.value = true;
}
function setShowOptions(options: ShowCURDModalOptions) {
  showOptions.value = options;
}
let selectedEquipmentKeys = ref<string[]>([]);
// 自定义删除方法
const getUserDeleteParams = (id) => {
  return id ? [id] : selectedEquipmentKeys.value;
};
const selectedRowKeys = ref<string[]>([]);
const curEquipmentId = ref<string>("");
const rowSelection = {
  type: "checkbox",
  selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys;
  },
};
function delEquipmentsFn() {
  showOptions.value = { action: CURDAction.DELETE, ids: selectedRowKeys.value, message: "您确定要删除已选设备吗？" };
}
function handleSuccess() {
  selectedRowKeys.value = [];
}
function editFn(row: EquipmentItem) {
  curEquipmentId.value = row.equipmentId;
}
const curEquipmentOption = ref<GatewayModalPropsOptions>({
  equipmentId: "",
  equipmentName: "",
  gatewayId: "",
  gatewayTypeId: "",
  equipmentTypeId: "",
});
const gatewayBindVisible = ref<boolean>(false);
function gatewaySetFn(row: EquipmentItem) {
  gatewayBindVisible.value = true;
  curEquipmentOption.value = {
    equipmentId: row.equipmentId,
    equipmentName: row.equipmentName,
    gatewayId: row.gatewayId,
    gatewayTypeId: row.gatewayTypeId,
    equipmentTypeId: row.equipmentTypeId,
  };
}
</script>
